package com.sky.aop;

import com.sky.anno.AutoFill;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Component
@Aspect
@Slf4j
public class AutoFillAspect {
    @Before("@annotation(com.sky.anno.AutoFill)")
    public void autoFillAspect(JoinPoint joinPoint){
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        AutoFill annotation = method.getAnnotation(AutoFill.class);
        OperationType value = annotation.value();
        Object[] args = joinPoint.getArgs();

        if(args==null||args.length==0){
            log.info("方法参数有误");
            return;
        }
        Object entry = args[0];
        LocalDateTime now = LocalDateTime.now();
        Long currentId = BaseContext.getCurrentId();
        if(OperationType.INSERT==value){
            try {
                Method setCreateTime = entry.getClass().getDeclaredMethod("setCreateTime", LocalDateTime.class);
                setCreateTime.invoke(entry,now);
                Method setCreateUser = entry.getClass().getDeclaredMethod("setCreateUser", Long.class);
                setCreateUser.invoke(entry,currentId);
                Method setUpdateTime = entry.getClass().getDeclaredMethod("setUpdateTime", LocalDateTime.class);
                setUpdateTime.invoke(entry,now);
                Method setUpdateUser = entry.getClass().getDeclaredMethod("setUpdateUser", Long.class);
                setUpdateUser.invoke(entry,currentId);
            }catch (Exception e){
                e.printStackTrace();
            }
        }else {
            try {
                Method setUpdateTime = entry.getClass().getDeclaredMethod("setUpdateTime", LocalDateTime.class);
                setUpdateTime.invoke(entry,now);
                Method setUpdateUser = entry.getClass().getDeclaredMethod("setUpdateUser", Long.class);
                setUpdateUser.invoke(entry,currentId);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}
